package com.tc.sftp;

import com.jcraft.jsch.*;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Properties;

public class SFTPUtil {
	
	/**
	 * 上传文件临时目录
	 */
	private String localDir;//本地路径
	private String host;//sftp服务器IP
	private int port;//sftp服务端口号
	private String username;//用户名
	private String password;//密码
	private String privateKey;//密钥文件路径
	private String passphrase;//密钥口令
	private String remoteDir;//sftp端路径
	
	private ChannelSftp sftp = null;

	public SFTPUtil(String host, int port, String username, String password, String localDir, String remoteDir){
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
		this.localDir = localDir;
		this.remoteDir = remoteDir;
		connect();
	}
	
	public SFTPUtil(String host, int port, String username, String privateKey, String passphrase, String localDir, String remoteDir) {
		super();
		this.localDir = localDir;
		this.host = host;
		this.port = port;
		this.username = username;
		this.privateKey = privateKey;
		this.passphrase = passphrase;
		this.remoteDir = remoteDir;
		connect();
	}
	
	/**
	 * 连接sftp服务器
	 * @return
	 */
	public void connect() {
		JSch jsch = new JSch();
		try {

			if (privateKey != null && !"".equals(privateKey)) {
                //使用密钥验证方式，密钥可以使有口令的密钥，也可以是没有口令的密钥
                if (passphrase != null && "".equals(passphrase)) {
                    jsch.addIdentity(privateKey, passphrase);
                } else {
                    jsch.addIdentity(privateKey);
                }
            }
            Session session = jsch.getSession(username, host, port);
            if (password != null && !"".equals(password)) {
                session.setPassword(password);
            }
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");// do not verify host key
            session.setConfig(sshConfig);
            // session.setTimeout(timeout);
            session.setServerAliveInterval(92000);
            session.connect();
            //参数sftp指明要打开的连接是sftp连接
            sftp = (ChannelSftp)session.openChannel("sftp");
            sftp.connect();
            
			if(StringUtils.isNotBlank(remoteDir)){
				sftp.cd(remoteDir);
			}
		
		} catch (Exception e) {
			throw new SystemException("SFTP连接发生异常:", e);
		}
	}

	/**
	 * 上传文件
	 * @param fileName  要上传的文件
	 */
	public void upload(String fileName) {
		String fullFileName = localDir + fileName;
		File file = null;
		FileInputStream fis = null;
		try {
			file = new File(fullFileName);
			fis = new FileInputStream(file);
			sftp.put(fis, file.getName());
		} catch (Exception e) {
			throw new SystemException("报送文件【" + fileName + "】上传时发生异常:", e);
		}finally{
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {}
			}
			//file.delete();//清除本地文件
		}
	}
	
	
	/**
	 * 下载文件
	 * @param directory	下载目录
	 * @param downloadFile	下载文件
	 * @param saveDirectory	本地保存路径
	 * @throws Exception
	 */
	public void download(String directory, String downloadFile, String saveDirectory)  { 
		String saveFile = saveDirectory + "//" + downloadFile; 
		try {
			this.sftp.cd(directory);
			File file = new File(saveFile); 
			this.sftp.get(downloadFile, new FileOutputStream(file)); 
		} catch (SftpException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
			throw new SystemException("SFTP连接发生异常:", e);
		} catch (FileNotFoundException e) {
			throw new SystemException("未找到的本地文件地址："+directory+"//"+downloadFile);
		} 
	} 

	
	
	
	
	/**
     * Disconnect with server
     */
	public void disconnected(){
        if (sftp != null) {
            try {
            	sftp.quit();
                sftp.getSession().disconnect();
            } catch (JSchException e) {
                e.printStackTrace();
            }
            sftp.disconnect();
        }
    }

	public static void main(String[] args) throws JSchException {
		SFTPUtil sf = new SFTPUtil("221.122.73.122", 10023, "", "", "D:/", "bfj/report/HZCB");
		//SFTPUtil sf = new SFTPUtil("192.168.129.72", 22, "java", "E:\\app\\java\\mypay\\bankGateway\\keyStore\\abc\\id_dsa", null, "E:/app/java/mypaytmp/provision/", "report");
		    
		sf.upload("py.txt");
//		sf.upload("test1.txt");
		sf.disconnected();
		System.out.println("上传成功！");
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRemoteDir(String remoteDir) {
		this.remoteDir = remoteDir;
	}

	public void setSftp(ChannelSftp sftp) {
		this.sftp = sftp;
	}

	public void setLocalDir(String localDir) {
		this.localDir = localDir;
	}

}

